<template>
	<view class="login_box">
		<view class="text_login">
			<!-- logo -->
			<image class="login_logo" src="../../static/logo/orange.png" alt="" />

			<!-- 表单区域 -->
			<view class="login_phone">
				<text>手机号</text>
				<input type="text" maxlength="11" v-model="userphone" />
			</view>
			<view class="login_code">
				<text>验证码</text>
				<input type="text" maxlength="4" v-model="usercode" />
				<view hover-class="touchOpacity" @click="getsms">{{sendstr}}</view>
			</view>

			<!-- 登录按钮 -->
			<view class="login_but" hover-class="touchOpacity">
				<text space="ensp" @click="login">登 录</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userphone: '',
				usercode: '',
				sendstr: '获取验证码',
				buffer: true
			}
		},
		methods: {
			login(){
				let phone = this.userphone
				let code = this.usercode
				let {value,time}=uni.getStorageSync('code')
				if (!/^1[3456789]\d{9}/.test(phone)) {
					this.$tool.tip('手机号格式有误！');
					return;
				}
				if(new Date().getTime() - time >20000000){
					this.$tool.tip('验证码已过期,请重新获取')
					return;
				}
				if(code!=value){
					this.$tool.tip('验证码错误！')
					return;
				}
				this.$api.reqsmslogin({
					phone
				})
				.then(res=>{
					uni.setStorageSync('userInfo',res.list)
					uni.setStorageSync('token',res.list.token)
					this.$tool.tip('登录成功','success')
					uni.switchTab({
						url:'../user/user'
					})
					console.log(res)
				})
				.catch(err=>console.log(err))
			},
			getsms() {
				if (this.buffer) {
					let phone = this.userphone
					if (!/^1[3456789]\d{9}/.test(phone)) {
						this.$tool.tip('手机号格式有误！');
						return;
					}
					this.$api.reqsms({phone})
					.then(res => {
						this.buffer = false
						uni.setStorageSync('code',{value:res.list.code,time:new Date().getTime()})
						let num = 10
						let t =setInterval(()=>{
							this.sendstr = `请${num}秒后发送`
							num--;
							if(num<0){
								this.sendstr='获取验证码',
								clearInterval(t)
								num=10
								this.buffer = true
							}
							
						},1000)
					})
					.catch(err => console.log(err))
				}else{
					this.$tool.tip("请稍后发送")
				}
			}
		}
	}
</script>

<style>
	/* 引入样式 */
	@import url("@/static/css/textlogin.css");
</style>
